#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    sc = new myScenr(this);//实例化场景对象
    s = score::getscore();//获取单例对象
    this->fen = 0;//初始化分数
    this->ui->graphicsView->setScene(sc);//设置2D显示器的场景为sc
    //关联按键与对应的槽函数
    connect(ui->start,SIGNAL(clicked()),this->sc,SLOT(start()));
    connect(ui->pause,SIGNAL(clicked()),this->sc,SLOT(spause()));
    connect(ui->stop,SIGNAL(clicked()),this->sc,SLOT(stop()));

    connect(this->s,SIGNAL(beat()),this,SLOT(updatascore()));//关联图元操作单例对象发送的击中信号与更新分数槽函数

    connect(this->sc,SIGNAL(clear()),this,SLOT(clearscore()));//sc发出的停止清屏信号和对应的槽函数
    connect(this->sc,SIGNAL(finshed()),this,SLOT(finshed_slot()));//时间耗尽发送的结束信号与对应的槽函数

    play = new QMediaPlayer(this);//用于播放背景音乐
    play->setMedia(QUrl("qrc:/music/pic/11638.mp3"));
    play->setVolume(50);
    play->play();
    pt_music = new QTimer(this);//每隔20s便重新播放背景音乐，达到循环播放的效果
    connect(this->pt_music,SIGNAL(timeout()),this,SLOT(playslot()));
    pt_music->start(20000);

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::closeEvent(QCloseEvent *event)//重写关闭事件，出现弹窗
{

    int ret = QMessageBox::question(this,"确定","真的要离开吗?","是","否");
    if(ret == 1)
    {
        event->ignore();
    }
}

void MainWindow::updatascore()//更新分数
{
    fen++;
    this->ui->lcdNumber->display(fen);
}

void MainWindow::clearscore()//清空分数
{
    fen = 0;
    this->ui->lcdNumber->display(fen);
}

void MainWindow::playslot()//重新播放背景音乐
{
    play->stop();
    play->play();
}

void MainWindow::finshed_slot()//时间耗尽的槽函数
{
    QString tip;
    if(this->ui->lcdNumber->value() >= 100)
    {
        tip = "恭喜您挑战成功！再来一局？";
    }else{
        tip = "挑战失败！\n是否重新开始？";
    }
    QMessageBox message(QMessageBox::Warning,"本局结束！",tip,QMessageBox::Yes|QMessageBox::No);
        if (message.exec()==QMessageBox::Yes)
        {
            this->sc->stop();
            this->sc->start();
        }
        else
        {
            this->close();
        }
}
